from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.conf import settings
import os
import shutil
# Create your models here.

DEFAULT_FORMAT = ".jpg"
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    head = models.CharField(max_length = 100)
    head160 = models.ImageField(upload_to="head_img",null=True,blank=True)
    create_time = models.DateField(auto_now = True,auto_now_add = False)
    note = models.URLField()
    address = models.TextField()
    resume = models.TextField()

    def save(self,*args,**kargs): 
        super(UserProfile, self).save(*args,**kargs)
        if not self.head160:
            return
        pw = self.head160.width
        ph = self.head160.height

        #extention = os.path.splitext(self.head)[1]
        path = settings.MEDIA_ROOT + "head_img/" + str(self.user.id) + "_160" + DEFAULT_FORMAT
        thumbnail_path = settings.MEDIA_ROOT + "head_img/" + str(self.user.id) + "_48" + DEFAULT_FORMAT
        if pw > 48 or ph > 48:
            pw = 48
            ph = 48
        else :
            shutil.copy2(path, thumbnail_path) 
            return

        image = Image.open(path)
        thumbnail = image.thumbnail((pw,ph),Image.ANTIALIAS)
        image.save(thumbnail_path,"jpeg")


    def save_without_img(self,*args,**kargs):
        super(UserProfile, self).save(*args,**kargs)


class PublicNotif(models.Model):
    content = models.TextField()
    def __unicode__(self):
        return self.content

class UserMessage(models.Model):
    user = models.ForeignKey(User)
    message_kind = models.IntegerField()
    detail_id = models.IntegerField()
    isviewed = models.BooleanField()

class UserCollect(models.Model):
    user = models.ForeignKey(User)
    message_kind = models.IntegerField()
    detail_id = models.IntegerField()
